<?php
/**
 * Prado Portal.
 *
 * @author Steen Rabol <steen.rabol@gmail.com>
 * @link http://www.pradoportal.dk/
 * @copyright Copyright &copy; 2006,2007,2008 Steen Rabol
 * @license http://www.pradoportal.dk
 * @version $Id: PortalEmailScambler.php 449 2011-01-05 14:00:33Z steen.rabol $
 *
 */

/**
 * @author Artūras Šlajus <x11@arturaz.afraid.org>
 * @license http://creativecommons.org/licenses/LGPL/2.1/ CC-GNU LGPL
 */

/**
 * MTEmailScrambler class.
 *
 * Writes down email encoded in HEX which browser decodes with help of
 * JavaScript.
 *
 * Only supports ASCII Names.
 *
 * Usage:
 * <code>
 * <com:MTEmailScrambler Email="some@email.com" />
 * <com:MTEmailScrambler Email="some@email.com" Name="Some Dude" />
 * </code>
 *
 * Thanks to Andrew Langland for algorithm.
 */
class PortalEmailScambler extends TControl
{

	public function render($writer)
	{
		if (! $this->getEmail())
			throw new TConfigurationException('Email property must be set.');
		$name = $this->getName();
		if (! $name)
			$name = $this->getEmail();

		$email = preg_replace("/\"/","\\\"", $this->getEmail());

		$old = "document.write('<a href=\"mailto:$email\">$name</a>')";

		$output = '';
		for ($i=0; $i < strlen($old); $i++)
		{
			$output .= '%' . bin2hex(substr($old,$i,1));
		}

		$writer->write(
			'<script language="javascript">eval(unescape("'
			. $output . '"))</script>'
		);
	}

	/**
	 * @return String Email
	 */
	public function getEmail()
	{
		return $this->getViewState('Email');
	}
	/**
	 * @param String Email
	 */
	public function setEmail($value)
	{
		$this->setViewState('Email', TPropertyValue::ensureString($value));
	}

	/**
	 * @return String Name
	 */
	public function getName()
	{
		return $this->getViewState('Name');
	}
	/**
	 * Set visible name. Renders Email if not set.
	 *
	 * @param String Name
	 */
	public function setName($value)
	{
		$this->setViewState('Name', TPropertyValue::ensureString($value));
	}

}
?>